package com.ljt.utils;


import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class IPParser {
    public static String getCity(String ip) {
		String url="http://api.map.baidu.com/location/ip?ak=0vVGTXqYEy5naXvNAABsYASR&ip="+ip;
		url=connect(url);
		JSONObject json= JSONObject.parseObject(url);
		try {
			String city=json.getString("city");
			if (city!=null&&!city.trim().isEmpty()) {
				return city.replace("市", "");
			}else{
				return "北京";
			}
		} catch (Exception e) {
			return "北京";
		}
	}
    public static String connect(String url){
		HttpURLConnection httpurlconnection = null;
		StringBuffer line=new StringBuffer();
		try {
			URL url2 = new URL(url);
			// 以get方式请求
			httpurlconnection = (HttpURLConnection) url2.openConnection();
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setDoInput(true);
			// 获取到输入流
			InputStreamReader inputStreamReader = new InputStreamReader(
					httpurlconnection.getInputStream());
			BufferedReader br = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = br.readLine()) != null) {
				line.append(str);
				line.append("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "-1";
		} finally {
			if (httpurlconnection != null)
				httpurlconnection.disconnect();
		}
		return line.toString();
	}
    public static void main(String[] args) {
		System.out.println(getCity("192.168.1.1"));
	}
}